package lhc.alg.top100;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * description: https://leetcode.cn/problems/binary-tree-level-order-traversal/
 *  二叉树的层数遍历
 * author: hongchen.liao
 * date:  2022/9/21
 */
public class _102_ {


     //Definition for a binary tree node.
     public class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode() {}
         TreeNode(int val) { this.val = val; }
         TreeNode(int val, TreeNode left, TreeNode right) {
             this.val = val;
             this.left = left;
             this.right = right;
         }
     }

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<>();
            if(root == null) return list;
            Queue<TreeNode> stack = new LinkedList<>();
            stack.offer(root);
            while(!stack.isEmpty()){
                int size = stack.size();
                List<Integer> sub = new ArrayList<>();
                for(int i = 0; i < size; i++){
                    TreeNode node = stack.poll();
                    sub.add(node.val);
                    if(node.left != null){
                        stack.offer(node.left);
                    }
                    if(node.right != null){
                        stack.offer(node.right);
                    }
                }
                list.add(sub);
            }
            return list;
        }
    }

}
